package com.jumi.microservice.mq;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jm.member.common.core.utils.DelFlag;
import com.jumi.microservice.controller.api.JmLevelUpController;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.dto.reponse.SalesReponse;
import com.jumi.microservice.dto.request.JmUserQueryRequest;
import com.jumi.microservice.dto.request.JmUserUpdateRequest;
import com.jumi.microservice.entity.*;
import com.jumi.microservice.enums.*;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.WrapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单售后消息队列
 *
 * @author 123
 */
@Component
public class OrderAfterSaleListener implements MessageListener {

    @Resource
    IJmUserFenxiaoService fenxiaoService;

    @Resource
    IJmUserSalesService salesService;

    @Resource
    IJmUserService userService;

    @Resource
    IJmUserLevelConfigService configService;

    @Resource
    IErrOrderAfterMsgService errOrderAfterMsgService;
    @Resource
    IJmGoldPromoterReviewService goldPromoterReviewService;

    @Resource
    IJmUserTeamService userTeamService;
    @Resource
    IJmUserLevelChangeLogService userLevelChangeLogService;

    Logger logger = LoggerFactory.getLogger(OrderAfterSaleListener.class);

    @Resource
    SendMessageHandler sendMessageHandler;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        logger.info("从orderAfterSale队列收到消息[{}]", new String(message.getBody()));
        try {
            //{buyNum=6, orderId=102, afterNum=7, skuId=11}
            String m = new String(message.getBody());
            JSONObject jsonObject = JSON.parseObject(m);
            Integer buyNum = jsonObject.getInteger("buyNum");
            Integer orderId = jsonObject.getInteger("orderId");
            Integer afterNum = jsonObject.getInteger("afterNum");
            Integer skuId = jsonObject.getInteger("skuId");
            Integer buyId = jsonObject.getInteger("buyerId");

            LocalDateTime now = LocalDateTime.now();

            JmUserFenxiao fenxiao = new JmUserFenxiao();
            fenxiao.setOrderId(orderId);
            fenxiao.setGid(skuId);
            fenxiao.setIsDel(CommonEnum.否);
            QueryWrapper wrapper = WrapperUtil.getWrapper(null, fenxiao);
            wrapper.ne("status", FenXiaoStatus.失效);


            List<JmUserFenxiao> list = fenxiaoService.list(wrapper);
            logger.info("购买数量[{}]订单ID[{}]售后数量[{}]商品ID[{}]查询到的符合条件数据量[{}]", buyNum, orderId, afterNum, skuId, list.size());
            for (JmUserFenxiao jmUserFenxiao : list) {
                JmUserUpdateRequest user = userService.getUserInfoById(jmUserFenxiao.getBuyerId());
                if (afterNum >= buyNum) {
                    jmUserFenxiao.setStatus(FenXiaoStatus.失效);
                    //推送收益变更消息
                    String hidenPhone = user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    sendShouyiChangeMessage(hidenPhone,jmUserFenxiao.getGoodsName(),jmUserFenxiao.getYongjin(),jmUserFenxiao.getUid());
                } else {
                    //售后数量小于购买数量时，需要重新计算佣金;
                    BigDecimal yongjin = jmUserFenxiao.getYongjin();
                    double v = yongjin.doubleValue();
                    //计算出单个商品的佣金
                    double single = NumberUtil.div(v, buyNum.doubleValue());
                    //计算出剩余没有售后的商品数量
                    buyNum -= afterNum;
                    double mul = NumberUtil.mul(single, buyNum.doubleValue());
                    yongjin = new BigDecimal(mul);
                    jmUserFenxiao.setYongjin(yongjin);
                    //推送收益变更消息
                    String hidenPhone = user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    sendShouyiChangeMessage(hidenPhone,jmUserFenxiao.getGoodsName(),yongjin,jmUserFenxiao.getUid());
                }
                jmUserFenxiao.setUpdateTime(now);
            }
            if (list.size() > 0) {
                fenxiaoService.updateBatchById(list);
            }
            JmUserSales sales = new JmUserSales();
            sales.setOrderId(orderId);
            sales.setGid(skuId);
            sales.setIsDel(CommonEnum.否);
            QueryWrapper salesQuery = WrapperUtil.getWrapper(null, sales);
            salesQuery.eq("status", SalesStatus.正常);

            List<JmUserSales> salesList = salesService.list(salesQuery);

            logger.info("购买数量[{}]订单ID[{}]售后数量[{}]商品ID[{}]查询到的符合条件数据量[{}]", buyNum, orderId, afterNum, skuId, salesList.size());
            for (JmUserSales userSales : salesList) {
                JmUserUpdateRequest user = userService.getUserInfoById(userSales.getBuyerId());
                logger.info("afterNum >= buyNum [{}]",afterNum >= buyNum);
                if (afterNum >= buyNum) {
                    userSales.setStatus(SalesStatus.失效);
                    //推送业绩变更消息
                    String hidenPhone = user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    sendYejiChangeMessage(hidenPhone,userSales.getGoodsName(),userSales.getPayGoodsPrice(),userSales.getUid());
                } else {
                    //售后数量小于购买数量时，需要重新计算业绩;
                    BigDecimal yeji = userSales.getPayGoodsPrice();
                    //计算出单个商品的佣金
                    BigDecimal single = NumberUtil.div(yeji,buyNum);
                    //计算出剩余没有售后的商品数量
                    buyNum -= afterNum;
                    yeji = NumberUtil.mul(single,buyNum).setScale(2,RoundingMode.DOWN);
                    //推送业绩变更消息
                    String hidenPhone = user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    sendYejiChangeMessage(hidenPhone,userSales.getGoodsName(),yeji,userSales.getUid());
                    userSales.setPayGoodsPrice(yeji);
                }
                userSales.setUpdateTime(now);
            }
            if (salesList.size() > 0) {
                salesService.updateBatchById(salesList);
            }

            for (JmUserSales userSales : salesList) {

                //如果用户是优秀店长，业绩未达标，降级
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.select("origin_level","level","id");
                queryWrapper.eq("id",userSales.getUid());

                JmUser one = userService.getOne(queryWrapper);

                Level level = one.getLevel();

                //如果用户是优秀店长和金牌推广商，业绩未达标，降级
                if (level.getValue().equals(3) || level.getValue().equals(4)) {

                    //初始等级大于当前等级不能降级
                    if (one.getOriginLevel().getValue() < level.getValue()) {

                        JmUserLevelConfig obj = configService.getById(level.getValue());

                        QueryWrapper salesWrapper = new QueryWrapper();

                        salesWrapper.eq("uid",userSales.getUid());
                        salesWrapper.eq("status",SalesStatus.正常);
                        //salesWrapper.select("ifnull(sum(pay_goods_price),0) as salesSum");

                        BigDecimal oneSalesSum = salesService.getSumSales(salesWrapper);

                        if (oneSalesSum.compareTo(obj.getSales()) == -1 ) {
                            //降级
                            GradeEnum gradeEnum = GradeEnum.降级;

                            //更新用户等级日志
                            JmUserLevelChangeLog changeLog=new JmUserLevelChangeLog(userSales.getUid(),one.getLevel(),Level.getLevelByValue(2),0,gradeEnum,LevelChangeEnum.业绩未达标降级
                                    ,0l,"业绩未达标",0l,"", DelFlag.normal,LocalDateTime.now(),LocalDateTime.now());
                            userLevelChangeLogService.save(changeLog);

                            //优秀店长降级为店长
                            if (level.getValue().equals(3)) {

                                one.setLevel(Level.getLevelByValue(2));
                            }else{ //金牌推广商降级为优秀店长

                                //将金牌推广商的审核改为不通过
                                QueryWrapper goldPromoterQueryWrapper = new QueryWrapper();

                                goldPromoterQueryWrapper.eq("member_id",userSales.getUid());

                                JmGoldPromoterReview goldOne = goldPromoterReviewService.getOne(goldPromoterQueryWrapper);

                                if (goldOne != null) {

                                    goldOne.setStatus(CheckStatus.未通过);
                                    goldOne.setMessage("降级到优秀店长，请重新申请升级");
                                    goldPromoterReviewService.updateById(goldOne);
                                }
                                one.setLevel(Level.getLevelByValue(3));
                            }


                            userService.updateById(one);

                            //获取用户的team信息
                            List<JmUserTeam> listTeam = userTeamService.getMySupers(userSales.getUid());
                            for (JmUserTeam jmUserTeam : listTeam) {
                                jmUserTeam.setLevel(Level.getLevelByValue(2));
                            }
                            if(listTeam.size()>0){userTeamService.updateBatchById(listTeam);}

                        }
                    }
                }
            }



        } catch (Exception e) {
            //如果处理出错，将消息存储到数据库再处理.
            ErrOrderAfterMsg errOrderAfterMsg = new ErrOrderAfterMsg();
            errOrderAfterMsg.setCreateTime(LocalDateTime.now());
            errOrderAfterMsg.setErrContent(e.getMessage());
            errOrderAfterMsg.setErrMsg(new String(message.getBody()));
            errOrderAfterMsg.setIsDel(CommonEnum.否);
            errOrderAfterMsgService.save(errOrderAfterMsg);
            logger.error("订单售后消息处理错误--->:" + e);
            return Action.ReconsumeLater;
        }
        logger.info("订单售后消息消费结束---->");
        return Action.CommitMessage;
    }

    /**
     * 业绩变更消息推送
     * @param name
     * @param goodsName
     * @param yeji
     * @param uid
     */
    public void sendYejiChangeMessage(String name,String goodsName, BigDecimal yeji, Integer uid) {
        //推送消息
        try {
            MessageTemplate template = sendMessageHandler.getMessageTemplate(MessageSendType.SALES_LOSE.getValue());
            Map map = new HashMap();
            map.put("name",name);
            map.put("goodsName",goodsName);
            map.put("yeji",yeji);
            String appMessageContent = StrUtil.format(template.getSmtAppContent(),map);
            String stationMessageContent = StrUtil.format(template.getSmtMessageContent(),map);;
            sendMessageHandler.sendMessage(appMessageContent, stationMessageContent, uid, MessageSendType.SALES_LOSE.getValue());
        } catch (Exception e) {
            logger.info("消息发送失败!");
        }
    }

    public void sendShouyiChangeMessage(String name,String goodsName, BigDecimal shouyi, Integer uid) {
        //推送消息
        try {
            MessageTemplate template = sendMessageHandler.getMessageTemplate(MessageSendType.INCOME_LOSE.getValue());
            Map map = new HashMap();
            map.put("name",name);
            map.put("goodsName",goodsName);
            map.put("shouyi",shouyi);
            String appMessageContent = StrUtil.format(template.getSmtAppContent(),map);
            String stationMessageContent = StrUtil.format(template.getSmtMessageContent(),map);;
            sendMessageHandler.sendMessage(appMessageContent, stationMessageContent, uid, MessageSendType.INCOME_LOSE.getValue());
        } catch (Exception e) {
            logger.info("消息发送失败!");
        }
    }



}

